import { Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';
import * as crypto from 'crypto';
import { FileService } from '../file/file.service';
import { File } from '../file/entities/file.entity';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class OssService {
    private readonly client: OSS;

    constructor(
        private readonly fileService: FileService,
        private configService: ConfigService
    ) {
        // 初始化 OSS 客户端
        this.client = new OSS({
            region: this.configService.get<string>('OSS_REGION') || 'cn-beijing',
            accessKeyId: this.configService.get<string>('OSS_ACCESS_KEY_ID') || 'LTAI5t5ttfNG7KVD39bthB57',
            accessKeySecret: this.configService.get<string>('OSS_ACCESS_KEY_SECRET') || 'fpv3My7W8bdQBCVei4BXTaTOhkPddv',
            bucket: this.configService.get<string>('OSS_BUCKET') || 'zhuguli-blog',
            endpoint:'oss-cn-beijing.aliyuncs.com'
        });
    }

    async uploadFile(bucketName: string, file: any, data: Buffer) {
        const lastDotIndex = file.originalname.lastIndexOf('.');
        const splitArray = [
            file.originalname.substring(0, lastDotIndex),
            file.originalname.substring(lastDotIndex + 1),
        ];
        const hash = crypto.createHash('md5').update(file.buffer).digest('hex');
        const originalName = `${hash}.${splitArray[1]}`;
        const fileEntity = new File();
        fileEntity.size = file.size / 1000;
        fileEntity.name = splitArray[0];
        fileEntity.type = splitArray[1];
        fileEntity.url = this.getUrl(bucketName, originalName);
        console.log(fileEntity.url)

        await this.client.put(`${bucketName}/${originalName}`, data);

        const flag = await this.fileService.isExist(fileEntity.url);
        if (flag.length < 1) {
            await this.fileService.create(fileEntity);
        }

        return fileEntity;
    }

    getUrl(bucketName: string, originalName: string) {
        const region = this.configService.get<string>('OSS_REGION') || 'oss-cn-hangzhou';
        const bucket = this.configService.get<string>('OSS_BUCKET') || bucketName;
        return `http://${bucket}.oss-${region}.aliyuncs.com/${bucketName}/${originalName}`;
    }
}
